import { app, BrowserWindow, desktopCapturer, dialog, ipcMain, screen } from 'electron'
import { writeFile } from 'fs'
import { join } from 'path'
import { v4 as uuidv4 } from 'uuid'
// 创建区域选择窗口
function createRegionSelectorWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize

  return new BrowserWindow({
    width,
    height,
    frame: false,
    transparent: true,
    alwaysOnTop: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  })
}
class ScreenRecordingApi {
  static recorders = new Map()
  // 获取可用的屏幕源
  static async getSources() {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['window', 'screen'],
        fetchWindowIcons: true
      })
      console.log(sources, '---cc--')

      return { success: true, sources }
    } catch (error: any) {
      // 打印完整错误信息（而非仅message）
      console.error('获取屏幕源失败:', error)
      // 兼容错误对象可能没有message的情况
      const errorMsg = error instanceof Error ? error.message : String(error)
      return { success: false, error: errorMsg || '未知错误（可能是权限问题）' }
    }
  }
  // 开始录制
  static async startRecording(options) {
    try {
      const { sourceId } = options
      const recorderId = uuidv4()

      // // 创建媒体流
      // const constraints = {
      //   audio,
      //   video: {
      //     mandatory: {
      //       chromeMediaSource: 'desktop',
      //       chromeMediaSourceId: sourceId,
      //       minWidth: 1280,
      //       maxWidth: 1920,
      //       minHeight: 720,
      //       maxHeight: 1080
      //     }
      //   }
      // }
      // 修正后
      const constraints = {
        audio: false,
        video: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: sourceId,
          minWidth: 1280,
          maxWidth: 1920,
          minHeight: 720,
          maxHeight: 1080
        } as MediaTrackConstraints
      } as MediaStreamConstraints
      // 确保 mediaDevices 存在
      if (!navigator.mediaDevices) {
        throw new Error('浏览器不支持媒体设备访问')
      }
      const stream = await navigator.mediaDevices.getUserMedia(constraints)

      // 创建媒体录制器
      const mimeType = options.videoFormat === 'mp4' ? 'video/mp4' : 'video/webm; codecs=vp9'

      const mediaRecorder = new MediaRecorder(stream, { mimeType })
      const chunks: BlobPart[] = []

      mediaRecorder.ondataavailable = (e: BlobEvent) => chunks.push(e.data)

      // 存储录制器信息
      this.recorders.set(recorderId, {
        mediaRecorder,
        stream,
        chunks,
        format: options.videoFormat || 'webm'
      })

      mediaRecorder.start()

      return { success: true, recorderId }
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  }
  // 暂停录制
  static pauseRecording(recorderId: string) {
    try {
      const recorder = this.recorders.get(recorderId)
      if (!recorder) {
        return { success: false, error: '录制器不存在' }
      }

      recorder.mediaRecorder.pause()
      return { success: true }
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  }
  // 继续录制
  static resumeRecording(recorderId: string) {
    try {
      const recorder = this.recorders.get(recorderId)
      if (!recorder) {
        return { success: false, error: '录制器不存在' }
      }

      recorder.mediaRecorder.resume()
      return { success: true }
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  }

  // 停止录制
  static async stopRecording(recorderId: string) {
    try {
      const recorder = this.recorders.get(recorderId)
      if (!recorder) {
        return { success: false, error: '录制器不存在' }
      }

      return new Promise((resolve) => {
        // 停止录制
        recorder.mediaRecorder.onstop = async () => {
          // 创建视频文件
          const blob = new Blob(recorder.chunks, {
            type: recorder.format === 'mp4' ? 'video/mp4' : 'video/webm'
          })

          // 转换为Buffer
          const buffer = Buffer.from(await blob.arrayBuffer())

          // 显示保存对话框
          const { filePath } = await dialog.showSaveDialog({
            title: '保存录制文件',
            defaultPath: `recording-${new Date().getTime()}.${recorder.format}`,
            filters: [
              {
                name: '视频文件',
                extensions: [recorder.format]
              }
            ]
          })

          if (filePath) {
            await writeFile(filePath, buffer, () => {})
            resolve({ success: true, path: filePath })
          } else {
            resolve({ success: false, error: '用户取消保存' })
          }

          // 清理资源
          recorder.stream.getTracks().forEach((track) => track.stop())
          this.recorders.delete(recorderId)
        }

        recorder.mediaRecorder.stop()
      })
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  }

  // 全屏截图
  static async takeFullScreenshot(options: any) {
    try {
      const { format = 'png' } = options
      const sources = await desktopCapturer.getSources({ types: ['screen'] })
      const constraints = {
        audio: false,
        video: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: sources[0].id,
          minWidth: 1280,
          maxWidth: 4096,
          minHeight: 720,
          maxHeight: 2160
        } as MediaTrackConstraints
      } as MediaStreamConstraints
      // 捕获主屏幕
      const stream = await navigator.mediaDevices.getUserMedia(constraints)

      // 创建视频元素用于捕获帧
      const video = document.createElement('video')
      video.srcObject = stream

      return new Promise((resolve) => {
        video.onloadedmetadata = async () => {
          // 创建画布并绘制视频帧
          const canvas = document.createElement('canvas')
          canvas.width = video.videoWidth
          canvas.height = video.videoHeight
          const ctx = canvas.getContext('2d')
          if (!ctx) {
            return
          }
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

          // 停止流
          stream.getTracks().forEach((track) => track.stop())

          // 获取图像数据
          const dataUrl = canvas.toDataURL(`image/${format}`)
          const buffer = Buffer.from(dataUrl.split(',')[1], 'base64')

          // 保存文件
          const { filePath } = await dialog.showSaveDialog({
            title: '保存截图',
            defaultPath: `screenshot-${new Date().getTime()}.${format}`,
            filters: [
              {
                name: '图像文件',
                extensions: [format]
              }
            ]
          })

          if (filePath) {
            await writeFile(filePath, buffer, () => {})
            resolve({ success: true, path: filePath })
          } else {
            resolve({ success: false, error: '用户取消保存' })
          }
        }
      })
    } catch (error: any) {
      return { success: false, error: error.message }
    }
  }

  // 区域截图
  static async takeRegionScreenshot() {
    const regionWindow = createRegionSelectorWindow()
    // regionWindow.reload(join(__dirname, '../../renderer/src/views/tools/regionSelector/index.html'))
    console.log(regionWindow)

    return '666'
    return new Promise((resolve) => {
      const regionWindow = createRegionSelectorWindow()

      // 加载区域选择器页面
      if (app.isPackaged) {
        regionWindow.loadFile(join(__dirname, '../../region-selector.html'))
      } else {
        const url = `http://localhost:${process.env['VITE_DEV_SERVER_PORT']}/region-selector.html`
        regionWindow.loadURL(url)
      }

      // 处理区域选择结果
      ipcMain.once('region-selected', async (_, region) => {
        try {
          regionWindow.close()

          const { x, y, width, height } = region

          // 获取屏幕源
          const sources = await desktopCapturer.getSources({ types: ['screen'] })
          const constraints = {
            audio: false,
            video: {
              chromeMediaSource: 'desktop',
              chromeMediaSourceId: sources[0].id,
              minWidth: width,
              maxWidth: width,
              minHeight: height,
              maxHeight: height
            } as MediaTrackConstraints
          } as MediaStreamConstraints
          // 创建媒体流
          const stream = await navigator.mediaDevices.getUserMedia(constraints)

          // 创建视频元素
          const video = document.createElement('video')
          video.srcObject = stream

          video.onloadedmetadata = async () => {
            // 创建画布并绘制选定区域
            const canvas = document.createElement('canvas')
            canvas.width = width
            canvas.height = height
            const ctx = canvas.getContext('2d')
            if (!ctx) {
              return
            }
            // 绘制视频帧的特定区域
            ctx.drawImage(video, x, y, width, height, 0, 0, width, height)

            // 停止流
            stream.getTracks().forEach((track) => track.stop())

            // 获取图像数据
            const dataUrl = canvas.toDataURL('image/png')
            const buffer = Buffer.from(dataUrl.split(',')[1], 'base64')

            // 保存文件
            const { filePath } = await dialog.showSaveDialog({
              title: '保存区域截图',
              defaultPath: `region-screenshot-${new Date().getTime()}.png`,
              filters: [
                {
                  name: 'PNG图像',
                  extensions: ['png']
                }
              ]
            })

            if (filePath) {
              await writeFile(filePath, buffer, () => {})
              resolve({ success: true, path: filePath })
            } else {
              resolve({ success: false, error: '用户取消保存' })
            }
          }
        } catch (error: any) {
          resolve({ success: false, error: error.message })
        }
      })

      // 处理取消选择
      ipcMain.once('region-canceled', () => {
        regionWindow.close()
        resolve({ success: false, error: '用户取消选择' })
      })
    })
  }
}
export default ScreenRecordingApi
